#############################################################################
#  Copyright (C) 2007 Boscovich, Maximiliano - mboscovich@gmail.com          #
#                                                                            #
#  This program is free software; you can redistribute it and/or modify      #
#  it under the terms of the GNU General Public License as published by      #
#  the Free Software Foundation; either version 3 of the License, or         #
#  (at your option) any later version. See tht GPL_Licence.txt for details.  #
#                                                                            #
#  This program is distributed in the hope that it will be useful,           #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              #
#  GNU General Public License for more details.                              #
#                                                                            #
##############################################################################

import sys
sys.path.append("../")

from sqlobject import dberrors
from formencode import Invalid

from view.Template_view import *
from model.packages import *
from model.tables import *
import logModule

class Template_controller(Ui_Template_view):

    def __init__(self,template=None):
        self.widget = QtGui.QDialog()
        self.setupUi(self.widget)
        # Connections
        self.widget.connect(self.pushButtonMustBeAdd,QtCore.SIGNAL("clicked()"),
                            self.MustBeAdd)
        self.widget.connect(self.pushButtonMayNotBeAdd,
                            QtCore.SIGNAL("clicked()"), self.MayNotBeAdd)
        self.widget.connect(self.pushButtonMayBeAdd,
                            QtCore.SIGNAL("clicked()"), self.MayBeAdd)
        self.widget.connect(self.pushButtonMustBeRemove,
                            QtCore.SIGNAL("clicked()"), self.MustBeRemove)
        self.widget.connect(self.pushButtonMayNotBeRemove,
                            QtCore.SIGNAL("clicked()"), self.MayNotBeRemove)
        self.widget.connect(self.pushButtonMayBeRemove,
                            QtCore.SIGNAL("clicked()"), self.MayBeRemove)
        self.widget.connect(self.pushButtonCancel,QtCore.SIGNAL("clicked()"),
                            QtCore.SLOT('close()'))
        self.widget.connect(self.tabWidgetAddTemplate,
                            QtCore.SIGNAL("currentChanged(int)"),
                                            self.Tab_change)
        self.widget.connect(self.pushButtonAdd,QtCore.SIGNAL("clicked()"),
                            self.add_or_edit_template)

        self.lineEditTemplateName.setEnabled(True)
        self.pushButtonAdd.setText("Agregar")

        if template <> None:
            self.editMode=True
            self.edit_view(template)
        else:
            self.editMode=False

    def add_or_edit_template(self):
        if self.editMode:
            self.edit_template()
        else:
            self.add_template()

    def edit_template(self):
        name        = str(self.lineEditTemplateName.text())
        description = str(self.textEditTemplateDescription.toPlainText())
        MustBe      = self.listWidgetToList( self.listWidgetTemplateMustBe )
        MayNotBe    = self.listWidgetToList( self.listWidgetTemplateMayNot )
        MayBe       = self.listWidgetToList( self.listWidgetTemplateMay )
        try:
            logModule.log("Modificando template "+name)
            template = Template.selectBy(Category=name)
            template[0].Description=description
            template[0].setPackagesMustHave( MustBe )
            template[0].setPackagesMayHave( MayBe )
            template[0].setPackagesMayNotHave( MayNotBe )
            logModule.log("Listo, modificado el template "+name)
            self.widget.close()
        except Invalid,e:
            logModule.log(e)
        except dberrors,dberr:
            logModule.log("Error al modificar el template: "+dberr)

    def edit_view(self, template):
        self.lineEditTemplateName.setText(template.Category)
        self.lineEditTemplateName.setEnabled(False)
        self.textEditTemplateDescription.setPlainText(template.Description)
        self.pushButtonAdd.setText("Modificar")
        self.load_packageList_on_widget(self.listWidgetTemplateMustBe,
                                        template.PackagesMustHave())
        self.load_packageList_on_widget(self.listWidgetTemplateMay,
                                        template.PackagesMayHave())
        self.load_packageList_on_widget(self.listWidgetTemplateMayNot,
                                        template.PackagesMayNotHave())

    def load_package_on_widget(self,widget,packages=[]):
        widget.reset()
        for package in packages:
            widget.addItem(package)

    def load_packageList_on_widget(self,widget,packages=[]):
        widget.reset()
        for package in packages:
            widget.addItem(package)

    def Tab_change(self):
        item_selected = self.tabWidgetAddTemplate.currentIndex()
        if item_selected == 1 and self.listWidgetTemplateMustBeAvaible.count()==0:
            self.load_package_avaible()

    def load_package_avaible(self):
        self.__class__.message = QtGui.QProgressDialog("cargando informacion de paquetes","Cancelar",0,4)
        self.__class__.message.setWindowModality(QtCore.Qt.WindowModal)
        self.__class__.message.forceShow()
        self.__class__.message.setValue(0)
        time.sleep(0.1)                                  
        allPackages=packages().getDbPackagesList('order')
        self.__class__.message.setValue(1)
        time.sleep(0.1)
        self.load_package_on_widget(self.listWidgetTemplateMustBeAvaible,
                                    allPackages)
        self.__class__.message.setValue(2)
        time.sleep(0.1)
        self.load_package_on_widget(self.listWidgetTemplateMayNotAvaible,
                                    allPackages)
        self.__class__.message.setValue(3)
        time.sleep(0.1)
        self.load_package_on_widget(self.listWidgetTemplateMayAvaible,
                                    allPackages)
        self.__class__.message.setValue(4)
        time.sleep(0.1)
        del(self.__class__.message)

    def list_widget_swap(self,origin,destiny):
        selection = origin.selectedItems()
        for item in selection:
            destiny.addItem(item.text())
            origin.takeItem(origin.row(item))
    
    def MustBeAdd(self):
        self.list_widget_swap(self.listWidgetTemplateMustBeAvaible,
                                self.listWidgetTemplateMustBe) 

    def MayNotBeAdd(self):
        self.list_widget_swap(self.listWidgetTemplateMayNotAvaible,
                                self.listWidgetTemplateMayNot) 
    def MayBeAdd(self):
        self.list_widget_swap(self.listWidgetTemplateMayAvaible,
                                self.listWidgetTemplateMay) 
    
    def MustBeRemove(self):
        self.list_widget_swap(self.listWidgetTemplateMustBe,
                                self.listWidgetTemplateMustBeAvaible) 
    
    def MayNotBeRemove(self):
        self.list_widget_swap(self.listWidgetTemplateMayNot,
                                self.listWidgetTemplateMayNotAvaible) 
    
    def MayBeRemove(self):
        self.list_widget_swap(self.listWidgetTemplateMay,
                                self.listWidgetTemplateMayAvaible) 

    def listWidgetToList(self,listWidget):
        list = []
        for i in range(listWidget.count()):
            list.append( str( listWidget.item(i).text() ) )
        return list

    def add_template(self):
        name        = str(self.lineEditTemplateName.text())
        description = str(self.textEditTemplateDescription.toPlainText())
        MustBe      = self.listWidgetToList( self.listWidgetTemplateMustBe )
        MayNotBe    = self.listWidgetToList( self.listWidgetTemplateMayNot )
        MayBe       = self.listWidgetToList( self.listWidgetTemplateMay )
        try:
            logModule.log("Creando template "+name)
            new_template = Template(Category=name, Description=description)
            new_template.setPackagesMustHave( MustBe )
            new_template.setPackagesMayHave( MayBe )
            new_template.setPackagesMayNotHave( MayNotBe )
            logModule.log("Listo!, creado el template "+name)
            self.widget.close()
        except Invalid,e:
            logModule.log(e)
        except dberrors.DuplicateEntryError:
            logModule.log("El template "+name+" ya existe")

    def deleteTemplate(self, template):
        template_to_delete = Template.selectBy(Category=template)
        template_to_delete[0].destroySelf()

    def editTemplate(self, template, description=None, MustBe=None,
                        MayBe=None, MayNotBe=None):
        template_to_edit = Template.selectBy(Category=template)
        if description != None:
            template_to_edit.Description = description
        if MustBe != None:
            template_to_edit.MustBe = MustBe
        if MayBe != None:
            template_to_edit.MayBe = MayBe
        if MayNotBe !=  None:
            template_to_edit.MayNotBe = MayNotBe


